package cn.maihe.elg.operation.web.business;

import cn.maihe.elg.operation.common.Constants;
import cn.maihe.elg.operation.config.ElgConfig;
import cn.maihe.elg.operation.exception.ErrorCode;
import cn.maihe.elg.operation.exception.SystemRuntimeException;
import cn.maihe.elg.operation.model.enums.AuthStatus;
import cn.maihe.elg.operation.model.enums.GuaranteeCategory;
import cn.maihe.elg.operation.model.enums.GuaranteeType;
import cn.maihe.elg.operation.model.enums.UserType;
import cn.maihe.elg.operation.model.vo.business.ListProjectInfoVO;
import cn.maihe.elg.operation.repository.entity.AcceptOrderInfoDO;
import cn.maihe.elg.operation.repository.entity.BidCustomerDO;
import cn.maihe.elg.operation.repository.entity.ProjectInfoDO;
import cn.maihe.elg.operation.repository.entity.ProjectInfoVo;
import cn.maihe.elg.operation.security.model.UserContext;
import cn.maihe.elg.operation.service.business.BidCustomerService;
import cn.maihe.elg.operation.service.business.ProjectInfoService;
import cn.maihe.elg.operation.service.order.AcceptOrderInfoService;
import cn.maihe.elg.operation.utils.*;
import cn.maihe.framework.starter.base.sql.PageBo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description 投标项目信息controller
 * @Author WJH
 * @Date 2021/03/25
 */
@Api(value = "投标项目信息管理", tags = "投标项目信息管理")
@RestController
@RequestMapping("/api")
@Slf4j
public class ProjectController {
    @Resource
    private ProjectInfoService projectInfoService;
    @Resource
    private AcceptOrderInfoService acceptOrderInfoService;
    @Resource
    private BidCustomerService bidCustomerService;
    @Resource
    private ElgConfig elgConfig;
    @Resource
    private DownloadExcelTool downloadExcelTool;

    @ApiOperation(value = "分页查询投标项目信息", notes = "根据投标项目标段编码、标段名称、投递投标文件截止日 分页查询")
    @RequestMapping(value = "/projects", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "页数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页大小", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "sectionCode", value = "标段编码", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "sectionName", value = "标段名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "bidOpenTimeRange", value = "投递投标文件截止日（startDate,endDate）", dataType = "String", paramType = "query"),
    })
    public PageBo<ListProjectInfoVO> pageList(int pageNo, int pageSize, ListProjectInfoVO vo) {
        return projectInfoService.selectPageBySql(pageNo, pageSize, vo);
    }

    @ApiOperation(value = "获取投标项目信息", notes = "根据投标项目信息id获取投标项目信息")
    @ApiImplicitParam(name = "id", value = "投标项目信息id", dataType = "long", paramType = "path", required = true)
    @RequestMapping(value = "/project/{id}", method = RequestMethod.GET)
    public ListProjectInfoVO getProject(@PathVariable Long id) {
        ListProjectInfoVO curVO = projectInfoService.getProjectInfoDetailById(id);
        if (curVO == null) {
            throw new SystemRuntimeException(ErrorCode.NOTEXISTS, "投标项目信息id");
        }
        return curVO;
    }

    @ApiOperation(value = "新增投标项目信息", notes = "新增投标项目信息")
    @RequestMapping(value = "/project", method = RequestMethod.POST)
    public void createProject(@Validated @RequestBody ProjectInfoVo vo) {
        ProjectInfoDO cDO = ProjectInfoDO.of(vo);
        cDO.setSectionCode(cDO.getProjectCode());
        cDO.setSectionName(cDO.getProjectName());
        cDO.setCenterId(Constants.CENTER_ID);
        cDO.setOrgId(Constants.ORG_ID);
        cDO.setId(IdGenerate.getId());
        //设置投标截止时间
        cDO.setBidIndate(this.buildBidIndate(vo.getBidOpenTime()));

        if (projectInfoService.existsSectionCode(cDO.getSectionCode(), cDO.getCenterId(), cDO.getOrgId(), null)) {
            throw new SystemRuntimeException(ErrorCode.EXISTS, "投标项目信息编码", vo.getSectionCode());
        }

        projectInfoService.insert(cDO);
    }

    @ApiOperation(value = "修改投标项目信息", notes = "根据投标项目信息id修改投标项目信息")
    @RequestMapping(value = "/project", method = RequestMethod.PUT)
    public void modifyProject(@Validated @RequestBody ProjectInfoVo vo) {
        ProjectInfoDO cDO = ProjectInfoDO.of(vo);
        cDO.setSectionCode(cDO.getProjectCode());
        cDO.setSectionName(cDO.getProjectName());
        Assert.notNull(vo.getId(), "投标项目主键Id不能为空");
        //设置投标截止时间
        cDO.setBidIndate(this.buildBidIndate(vo.getBidOpenTime()));
        if (projectInfoService.existsSectionCode(cDO.getSectionCode(), cDO.getCenterId(), cDO.getOrgId(), vo.getId())) {
            throw new SystemRuntimeException(ErrorCode.EXISTS, "投标项目信息编码", vo.getSectionCode());
        }

        projectInfoService.updateById(cDO);
    }

    @ApiOperation(value = "删除投标项目信息", notes = "根据投标项目信息id删除投标项目信息")
    @ApiImplicitParam(name = "id", value = "投标项目信息id", dataType = "long", paramType = "path", required = true)
    @RequestMapping(value = "/project/{id}", method = RequestMethod.DELETE)
    public void deleteProject(@PathVariable Long id) {
        if (projectInfoService.existsProjectLinkedAcceptOrder(id)) {
            throw new SystemRuntimeException(ErrorCode.NONDELETE, "投标项目信息已存在关联受理订单");
        }
        projectInfoService.deleteById(id);
    }


    @ApiOperation(value = "投标客户申请委托", notes = "投标客户申请委托")
    @RequestMapping(value = "/bidProject/bid", method = RequestMethod.POST)
    public void bidProject(@Validated @RequestBody ListProjectInfoVO vo) {
        UserContext userContext = UserContextUtil.getUserContext();
        if (UserType.BIDDER.getType() != userContext.getUserType()) {
            throw new SystemRuntimeException(ErrorCode.ERROR, "非投标客户,无法操作");
        }

        //1.创建受理订单 默认委托状态失败且受理订单状态为null
        BidCustomerDO bidCustomerDO = bidCustomerService.selectById(userContext.getBidderId());

        AcceptOrderInfoDO acceptOrderInfoDO = null;
        if (vo.getAcceptOrderId() != null) {
            acceptOrderInfoDO = acceptOrderInfoService.selectById(vo.getAcceptOrderId());
            acceptOrderInfoDO.setStatus(null);
            acceptOrderInfoDO.setAuthStatus(AuthStatus.FAILURE.getStatus());
            acceptOrderInfoService.updateById(acceptOrderInfoDO);
        } else {
            String tranceId = IdGenerate.genTranceId();
            acceptOrderInfoDO = AcceptOrderInfoDO.builder()
                    .id(IdGenerate.getId()).centerOrderId(tranceId).acceptOrderNo(tranceId)
                    .orgId(Constants.ORG_ID).centerId(Constants.CENTER_ID).institutionId(Constants.INSTITUTION_ID).centerOrderTime(DateUtil.getDatetime())
                    .projectId(vo.getId()).projectName(vo.getProjectName()).sectionName(vo.getSectionName())
                    .bidCustomerId(bidCustomerDO.getId()).bidCustomerName(bidCustomerDO.getBidderName())
                    .bidIndate(vo.getBidIndate()).guaranteeType(GuaranteeType.GUARANTEE.getTypeStr())
                    .guaranteeCategory(GuaranteeCategory.BID.getCategoryStr()).guaranteeFee(vo.getGuaranteeFee())
                    .status(null).authStatus(AuthStatus.FAILURE.getStatus())
                    .build();
            acceptOrderInfoService.insert(acceptOrderInfoDO);
        }

//        acceptOrderInfoService.createSqContract(acceptOrderInfoDO);


    }

    /**
     * 通过开标时间获取投标截止时间
     */
    private Date buildBidIndate(Date bidOpenTime) {
        Long beforeHours = elgConfig.getBeforeHours();
        if (bidOpenTime != null) {
            return Date.from(bidOpenTime.toInstant().minus(beforeHours, ChronoUnit.HOURS));
        }
        return null;
    }

    @RequestMapping(value = "/project/download", method = RequestMethod.POST)
    public void downloadProject(HttpServletResponse response, @RequestBody ListProjectInfoVO vo) {
        PageBo<ListProjectInfoVO> pageBo = projectInfoService.selectPageBySql(1, DownloadExcelTool.maxRowNum, vo);
        List<ListProjectInfoVO> list = pageBo.getList().stream().map(l -> {
//            l.setBidBondYuan(StringUtil.toYuan(l.getBidBond()));
            return l;
        }).collect(Collectors.toList());
        downloadExcelTool.downloadByTemplateName("projectReport.xlsx", "投标项目", response, list, null);
    }



}
